package com.wqh.article.command;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.wqh.article.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @author wanqh
 * @date 2018/01/12 14:27
 * @description:
 */
public class UserCommand extends HystrixCommand<User> {

    private final Logger logger =  LoggerFactory.getLogger(UserCommand.class);
    private RestTemplate restTemplate;
    private Long id;

    public UserCommand(RestTemplate restTemplate,Long id){
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("userGroup")));
        this.restTemplate = restTemplate;
        this.id = id;
    }

    @Override
    protected User getFallback() {
        Throwable e = getExecutionException();
        logger.info(">>>>>>>>>>>>>>>>>>>>>异常{}<<<<<<<<<<<<<<<<",e.getMessage());
        System.out.println(e);
        return new User(-1L,"",-1);
    }

    @Override
    protected User run() throws Exception {
        logger.info(">>>>>>>>>>>>>自定义HystrixCommand请求>>>>>>>>>>>>>>>>>>>>>>>>>>");
        return restTemplate.getForObject("http://USER-SERVICE/user/{1}",User.class,id);
    }

    @Override
    protected String getCacheKey() {
        return String.valueOf(id);
    }
}
